import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '../utils/request.js';

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  // 登录状态
  const isLoggedIn = ref(false)
  // token
  const token = ref('')

  // 从本地存储恢复状态
  const restoreState = () => {
	const storedUserInfo = uni.getStorageSync('userInfo')
	const storedToken = uni.getStorageSync('token')

	if (storedUserInfo && storedToken) {
	  userInfo.value = JSON.parse(storedUserInfo)
	  token.value = storedToken
	  isLoggedIn.value = true
	}
  }

  // 保存状态到本地存储
  const saveState = () => {
	uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
	uni.setStorageSync('token', token.value)
  }

  // 清除状态
  const clearState = () => {
	userInfo.value = null
	token.value = ''
	isLoggedIn.value = false
	uni.removeStorageSync('userInfo')
	uni.removeStorageSync('token')
  }

  // 微信登录
  const loginByWechat = async (code,encryptedData,iv) => {
	try {
	  // 调用微信登录接口
	  const response = await request({
		url: '/app/user/login/mini',
		method: 'POST',
		data: {
		  code,
		  encryptedData,
		  iv
		}
	  })

	  const { userInfo: info, token: newToken } = response.data
	  userInfo.value = info
	  token.value = newToken
	  isLoggedIn.value = true
	  saveState()
	} catch (error) {
	  console.error('微信登录失败:', error)
	  throw error
	}
  }

  // 手机验证码登录
  const loginByPhone = async (phone, code) => {
	try {
	  // TODO: 调用手机验证码登录接口
	  const response = await uni.request({
		url: '/api/auth/phone',
		method: 'POST',
		data: { phone, code }
	  })

	  const { userInfo: info, token: newToken } = response.data
	  userInfo.value = info
	  token.value = newToken
	  isLoggedIn.value = true
	  saveState()
	} catch (error) {
	  console.error('手机验证码登录失败:', error)
	  throw error
	}
  }

  //账号密码登录
  const loginByAccount = async (username, password,captchaId,verifyCode) => {
	try {
	  // TODO: 调用账号密码登录接口
	  const response = await request({
		url: '/app/user/login/username',
		method: 'POST',
		data: { username, password,captchaId, verifyCode}
	  })

	  const { userInfo: info, token: newToken } = response.data
	  userInfo.value = info;
	  token.value = newToken;
	  isLoggedIn.value = true;
	  saveState();
	} catch (error) {
	  console.error('账号密码登录失败:' , error );
	  throw error;
	}
  }

  // 退出登录
  const logout = async () => {
	try {
	  const response = await request({
		url: '/app/user/login/logout',
		method: 'POST',
	  });
	  return response.data;
	} catch (error) {
	  console.error('退出登录失败:', error);
	  throw error;
	}
  }

  // 注销账户
  const deleteAccount = async () => {
	try {
	  const response = await request({
		url: '/app/user/info/logoff',
		method: 'POST',
	  });
	  clearState();
	  return response.data;
	} catch (error) {
	  console.error('注销账户失败:', error);
	  throw error;
	}
  }

  // 不需要登录的页面
  const publicPages = [
	'pages/login/index',
	'pages/register/index',
	'pages/index/index'  // 首页
  ]

  // 检查登录状态
  const checkLoginStatus = () => {
	// 获取当前页面路径
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const currentPath = currentPage ? currentPage.route : ''


	// 如果当前页面是公开页面，直接返回
	if (publicPages.includes(currentPath)) {
	  return true
	}

	// 检查登录状态
	if (!isLoggedIn.value) {
	  console.log('未登录，跳转到登录页面')
	  // 使用setTimeout确保页面已经加载完成
	  setTimeout(() => {
		uni.redirectTo({
		  url: '/pages/login/index',
		  fail: (err) => {
			console.error('跳转失败:', err)
			// 如果redirectTo失败，尝试使用reLaunch
			uni.reLaunch({
			  url: '/pages/login/index'
			})
		  }
		})
	  }, 100)
	  return false
	}

	return true
  }

  // 处理token失效
  const handleTokenExpired = () => {
	clearState()
	uni.showToast({
	  title: '登录已过期，请重新登录',
	  icon: 'none',
	  duration: 2000
	})
	setTimeout(() => {
	  uni.reLaunch({
		url: '/pages/login/index'
	  })
	}, 2000)
  }

  // 初始化时恢复状态
  restoreState()

  //获取图片验证码
  const getImgCode = async () => {
	try {
	  const response = await request({
		url: '/app/user/login/captcha',
		method: 'GET',
		data:{
		  height: 45,
		  width: 150,
		  color: '#2c3142'
		}
	  });
	  return response.data;
	} catch (error) {
	  console.error('获取图片验证码失败:', error);
	  throw error;
	}
  }

  //发送短信验证码
  const sendSmsCode = async (phone,captchaId,code) => {
	try {
	  const response = await request({
		url: '/app/user/login/smsCode',
		method: 'POST',
		data: { phone,captchaId,code }
	  });
	  return response.data;
	} catch (error) {
	  console.error('发送短信验证码失败:', error);
	  throw error;
	}
  }

  //注册用户
  const register = async (params) => {
	try {
	  const response = await request({
		url: '/app/user/login/register',
		method: 'POST',
		data: params
	  });
	  return response.data;
	} catch (error) {
	  console.error('注册用户失败:', error);
	  throw error;
	}
  }

  //邮箱验证码注册
  const registerByEmail = async (params) => {
	try {
		const response = await request({
			url: '/app/user/login/register-email',
			method: 'POST',
			data: {
				...params,
			}
		});
		return response.data;
	} catch (error) {
		console.error('邮箱验证码注册失败:', error);
		throw error;
	}
  }

  //发送邮箱验证码
  const sendEmailCode = async (body:{email:string,type:Number}) => {
	// type: 类型 0-注册 1-修改密码 2-绑定邮箱
	try {
		const response = await request({
			url: '/app/user/comm/emailCode',
			method: 'POST',
			data: body
		});
		return response.data;
	} catch (error) {
		console.error('发送邮箱验证码失败:', error);
		throw error;
	}
  }

  // 更新用户信息
  const updateUserInfo = async (info) => {
	try {
		const response = await request({
			url: '/app/user/info/updatePerson',
			method: 'POST',
			data: info
		})

		// 更新本地用户信息
		userInfo.value = {
			...userInfo.value,
			...info
		}
		saveState()

		return response.data
	} catch (error) {
		console.error('更新用户信息失败:', error)
		throw error
	}
  }

  //邮箱登录
  const loginByEmail = async (params) => {
	try {
	  const response = await request({
		url: '/app/user/login/email',
		method: 'POST',	
		data: params
	  });
	  
	  const { userInfo: info, token: newToken } = response.data
	  userInfo.value = info;
	  token.value = newToken;
	  isLoggedIn.value = true;
	  saveState();

	  return response.data;
	} catch (error) {
	  console.error('邮箱登录失败:', error);
	  throw error;
	}
  }

  //修改密码
  const changePwdByEmail = async (params) => {
	try {
		const response = await request({
			url: '/app/user/login/update-password',
			method: 'POST',
			data: {
				...params,
			}
		})
		return response.data;
	} catch (error) {
		console.error('修改密码失败:', error);
		throw error;
	}
  }

  // 通过邮箱查找用户信息
  const fetchUserByEmail = async (email) => {
	try {
	  console.log(`fetchUserByEmail_. email: ${email}`);
	  const response = await request({
		url: '/app/user/info/getByEmail',
		method: 'GET',
		data: { email }
	  });
	  // response.data 结构: { code, data, message }
	  // data 可能为 null 或 { nickname, ... }
	  console.log(`fetchUserByEmail_. response: ${JSON.stringify(response.data)}`);
	  return response.data || null;
	} catch (error) {
	  // 404 或其他异常, 统一返回 null
	  console.log(`fetchUserByEmail_. error: ${error}`);
	  return null;
	}
  };

  //绑定邮箱
  const bindEmail = async (info) => {
	try {
		const response = await request({
			url: '/app/user/info/bindEmail',
			method: 'POST',
			data: info
		})
		// 更新本地用户信息
		userInfo.value = {
			...userInfo.value,
			...info
		}
		saveState()
		return response.data
	} catch (error) {
		console.error('绑定邮箱失败:', error);
		throw error;
	}
}

//解绑邮箱
const unBindEmail = async()=>{
	try {
		const response = await request({
			url: '/app/user/info/unBindEmail',
			method: 'POST',
		})
		// 更新本地用户信息
		userInfo.value = {
			...userInfo.value,
			email:null,
		}
		saveState()
		return response.data
	} catch (error) {
		console.error('解绑邮箱失败:', error);
		throw error;
	}
}

  return {
	userInfo,
	isLoggedIn,
	token,
	loginByWechat,
	loginByPhone,
	loginByAccount,
	getImgCode,
	sendSmsCode,
	register,
	registerByEmail,
	logout,
	deleteAccount,
	checkLoginStatus,
	clearState,
	handleTokenExpired,
	updateUserInfo,
	sendEmailCode,
	loginByEmail,
	changePwdByEmail,
	fetchUserByEmail,
	bindEmail,
	unBindEmail
  }
})